package dyyx.drools.demo1;

import java.io.StringReader;
import java.util.Collection;

import org.drools.KnowledgeBase;
import org.drools.KnowledgeBaseFactory;
import org.drools.builder.KnowledgeBuilder;
import org.drools.builder.KnowledgeBuilderFactory;
import org.drools.builder.ResourceType;
import org.drools.definition.KnowledgePackage;
import org.drools.io.ResourceFactory;
import org.drools.runtime.StatelessKnowledgeSession;

import dyyx.Utils;

public class Demo1Main {

	public static void main(String[] args) throws Exception {		
		String drl = Utils.readFromClassPath("drools/demo1.drl", null);	
		// 创建知识库
		KnowledgeBuilder kbuilder = KnowledgeBuilderFactory.newKnowledgeBuilder();
		long start = System.currentTimeMillis();
		// 加载drl规则文件
		kbuilder.add(ResourceFactory.newReaderResource(new StringReader(drl)),ResourceType.DRL);
		long end = System.currentTimeMillis();
		long time = end - start;
		System.out.println("time1="+time);

		start = System.currentTimeMillis();
		// 从知识库中获取规则包
		Collection<KnowledgePackage> pkgs = kbuilder.getKnowledgePackages();
		end = System.currentTimeMillis();
		time = end - start;
		System.out.println("time2="+time);
		
		start = System.currentTimeMillis();
		// 规则引擎添加规则包，添加相应的规则处理逻辑
		KnowledgeBase kbase = KnowledgeBaseFactory.newKnowledgeBase();
		end = System.currentTimeMillis();
		time = end - start;
		System.out.println("time3="+time);
		
		start = System.currentTimeMillis();
		kbase.addKnowledgePackages(pkgs);
		end = System.currentTimeMillis();
		time = end - start;
		System.out.println("time4="+time);
		
		start = System.currentTimeMillis();
		// 创建规则引擎执行会话
		StatelessKnowledgeSession session = kbase.newStatelessKnowledgeSession();
		
		end = System.currentTimeMillis();
		time = end - start;
		System.out.println("time5="+time);
		
		RuleHandler ruleHandler = new RuleHandler();
		
		// 设置全局变量， 这里传入的对象类型要与DRL文件中声明的一致
		session.setGlobal("rule_handler",ruleHandler);
		
        RuleContext context = new RuleContext();	
		context.setName("tiger");
		context.setAge(9);
		// 装载数据对象用于规则判断，执行规则引擎
		session.execute(context);
		System.out.println(context);
		
		context = new RuleContext();	
		context.setName("tiger");
		context.setAge(18);
		// 装载数据对象用于规则判断，执行规则引擎
		session.execute(context);
		System.out.println(context);
		
		
		context = new RuleContext();	
		//  ruleHandler 不会运行 
		context.setName("cat");
		context.setAge(18);
		// 装载数据对象用于规则判断，执行规则引擎
		session.execute(context);
		System.out.println(context);
		
	}
}
